package cc.vicp.djx314.starfood.web.manager;

import java.util.Iterator;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cc.vicp.djx314.starfood.domain.account.Manager;
import cc.vicp.djx314.starfood.domain.account.Personnel;
import cc.vicp.djx314.starfood.service.account.AccountService;
import cc.vicp.djx314.starfood.service.account.ManagerService;
import cc.vicp.djx314.starfood.service.account.PersonnelService;

@Controller
public class ManagerLoginController {
	public static final Logger logger = LoggerFactory.getLogger(ManagerLoginController.class);

	@Autowired
	private ManagerService managerService;

	/*@RequestMapping(value = "/loginpage/manager", method = RequestMethod.GET)
	public String personnelLoginPage() {
		return "customer/manager/managerlogin";
	}*/

	@RequestMapping(value = "/login/manager/ok", method = RequestMethod.GET)
	public String loginOk(HttpSession session) {
		String returnRedirect = null;
		Object principal =  SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String username = null;
		boolean isManager = false;
		if(principal instanceof UserDetails){
			username =((UserDetails)principal).getUsername();
			Iterator<? extends GrantedAuthority> it = ((UserDetails)principal).getAuthorities().iterator();
			String authority = "";
			while(it.hasNext()){
				authority = ((GrantedAuthority)it.next()).getAuthority();
				if (AccountService.ROLE_MANAGER.equals(authority)) {
					isManager = true;
				}
			}
		}
		if (isManager == false) {
			returnRedirect = "redirect:/logout/errorurl";
		} else {
			try {
				Manager manager = managerService.getManagerInfoForSession(username);
				session.setAttribute("loginManager", manager);
				returnRedirect = "redirect:/login/manager/success";
			} catch (Exception e) {
				logger.error("由已知user账号搜索对应user发生错误,应该是数据库问题", e);
				returnRedirect = "redirect:/logout/errordatabase";
			}
		}
		return returnRedirect;
	}

	@RequestMapping(value = "/login/manager/success", method = RequestMethod.GET)
	public String loginSuccessRedirect(HttpSession session) {
		//这里暂时改一改,直接去index
		//return "customer/user/loginsuccess";
		return "redirect:/manager/count/index";
	}
}